<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="12">
        <div class="title">{{ form.projectName }} 考勤记录</div>
      </el-col>
    </el-row>
    <el-form ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="mini">
      <el-form-item label="考勤月份">
        <el-date-picker v-model="queryParams.dateMonth" format="yyyy 年 MM 月" placeholder="选择月" type="month"
          value-format="yyyy-MM-dd" @change="handleQuery">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <div @mousedown="startDrag" @mouseup="stopDrag" @mousemove="handleDrag" @mouseleave="stopDrag">
      <el-table :data="form.staffList" ref="table" border max-height="1000">
        <el-table-column v-if="form.projectStatus == 2" align="center" fixed="left" label="项目小组" prop="groupName"
          width="100px;">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.cld_project_groups" :value="scope.row.groupName" />
          </template>
        </el-table-column>
        <el-table-column v-if="form.projectStatus == 2" align="center" fixed="left" label="岗位编号" prop="projectPostNo"
          width="200" />
        <el-table-column v-if="form.projectStatus == 2" align="center" fixed="left" label="岗位名称" prop="projectPostName">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.cld_project_post" :value="scope.row.projectPostName" />
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="left" label="员工姓名" prop="staffName">
          <template slot-scope="scope">
            <el-link type="primary" @click="handleGetStaffView(scope.row)">{{ scope.row.staffName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column v-for="item in form.calendarList" :key="item.calendarId" :label="item.calendayDay + '日'"
          align="center" width="300">
          <template slot-scope="{ row }">
            <div v-if="row.dayData[item.calendayDate]" v-html="assemblyData(row.dayData[item.calendayDate])">

            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 个人排休预览 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="open" title="个人月度考勤表" width="80%">
      <el-descriptions :column="5" border>
        <el-descriptions-item label="岗位名称">
          <dict-tag :options="dict.type.cld_project_post" :value="staffForm.projectPostName" />
        </el-descriptions-item>
        <el-descriptions-item label="员工姓名">{{ staffForm.staffName }}</el-descriptions-item>
      </el-descriptions>
      <el-calendar :value="queryParams.dateMonth" @input="handleEditAtt">
        <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
        <template slot="dateCell" slot-scope="{date, data}">
          {{ data.day.split('-').slice(1).join('-') }}
          <div v-if="staffForm[data.day]" class="attDetails" v-html="assemblyData(staffForm[data.day])">

          </div>
        </template>
      </el-calendar>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :visible.sync="attOpen" title="修改考勤" width="500px">
      <el-form ref="form" :model="attFrom" label-position="top" label-width="80px" size="mini">
        <el-row v-if="attFrom.isLeave == 0 && attFrom.isInThisProject == 0 && attFrom.isOutExtProject == 0"
          :gutter="20">
          <el-col :span="12">
            <el-form-item label="上班打卡1">
              <el-time-picker v-model="attFrom.goToWorkTime1" :picker-options="{

              }" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下班打卡1">
              <el-time-picker v-model="attFrom.goOffWorkTime1" :picker-options="{

              }" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上班打卡2">
              <el-time-picker v-model="attFrom.goToWorkTime2" :picker-options="{
                selectableRange: attFrom.echoGoOffWorkTime1 + '-' + attFrom.echoGoToWorkTime2
              }" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下班打卡2">
              <el-time-picker v-model="attFrom.goOffWorkTime2" :picker-options="{
              }" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上班打卡3">
              <el-time-picker v-model="attFrom.goToWorkTime3" :picker-options="{
              }" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下班打卡3">
              <el-time-picker v-model="attFrom.goOffWorkTime3" :picker-options="{
              }" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="attFrom.isLeave == 1" :gutter="20">
          <el-col :span="12">
            <el-form-item label="请假开始时间">
              <el-time-picker v-model="attFrom.leaveStartTime" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假结束时间">
              <el-time-picker v-model="attFrom.leaveEndTime" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="attFrom.isInThisProject == 1" :gutter="20">
          <el-col :span="12">
            <el-form-item label="加班开始时间">
              <el-time-picker v-model="attFrom.thisStartTime" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加班结束时间">
              <el-time-picker v-model="attFrom.thisEndTime" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="attFrom.isOutExtProject == 1">
          <el-col :span="24">
            <el-form-item label="调出项目">
              <el-select v-model="form.newProjectId" placeholder="请选择">
                <el-option v-for="item in projectOptions" :key="item.projectId" :label="item.projectName"
                  :value="item.projectId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加班开始时间">
              <el-time-picker v-model="attFrom.extStartTime" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加班结束时间">
              <el-time-picker v-model="attFrom.extEndTime" format='HH:mm' value-format='HH:mm'>
              </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="attOpen = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAttendance, getCalendarByStaffId, getTableCalendarList, updateAttendance } from '@/api/cld/attendance'
import { getList } from '@/api/cld/project'

export default {
  name: "viewAttendance",
  dicts: ["cld_project_post", 'cld_project_groups'],
  data() {
    return {
      // 项目排休情况
      list: [],
      // 查询条件
      queryParams: {
        dateMonth: new Date(),
        attendanceYear: new Date().getFullYear(),
        attendanceMonth: new Date().getMonth() + 1,
        projectId: this.$route.params.projectId,
      },
      // 项目id
      projectId: null,
      form: {},
      open: false,
      staffForm: {},
      // 考勤信息修改
      attOpen: false,
      // 考勤信息
      attFrom: {},
      // 项目列表
      projectOptions: []
    };
  },
  created() {
    this.projectId = this.$route.params && this.$route.params.projectId;
    if (this.projectId) {
      this.handleGetProjectList();
      this.handleGetAttendance();
    }
  },
  methods: {
    // 查询当月考勤记录
    handleGetAttendance() {
      getTableCalendarList(this.queryParams).then(res => {
        this.form = res.data;
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.table.bodyWrapper.scrollLeft = (new Date().getDate() - 1) * 250
          }, 1000)//必须是1000以上 才能生效
        });
      })
    },
    // 查询项目列表
    handleGetProjectList() {
      getList().then(res => {
        this.projectOptions = res.data;
      })
    },
    // 个人考勤预览
    handleGetStaffView(row) {
      getCalendarByStaffId({
        projectId: this.projectId,
        staffId: row.staffId,
        attendanceYear: this.queryParams.attendanceYear,
        attendanceMonth: this.queryParams.attendanceMonth
      }).then(res => {
        this.staffForm = res.data;
        this.open = true;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.dateMonth) {
        this.queryParams.attendanceYear = this.parseTime(this.queryParams.dateMonth, '{yyyy}');
        this.queryParams.attendanceMonth = this.parseTime(this.queryParams.dateMonth, '{mm}');
      }
      this.handleGetAttendance();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 修改考勤
    handleEditAtt(data) {
      let obj = this.staffForm[this.parseTime(data, '{y}-{m}-{d}')];
      if (!obj) {
        this.$message.error('暂无考勤信息！');
      }
      getAttendance(obj.attendanceId).then(res => {
        this.attFrom = res.data;
        this.attOpen = true;
      })

    },
    // 考勤修改提交
    onSubmit() {
      updateAttendance(this.attFrom).then(res => {
        this.$modal.msgSuccess("操作成功");
        this.attOpen = false;
        this.handleGetStaffView(this.attFrom);
        this.resetQuery()
      })
    },
    // 组装日历打卡请假加班数据
    assemblyData(data) {
      let returnStr = '';
      if (data.isRest == 1 && data.isInThisProject == 0 && data.isOutExtProject == 0) {
        returnStr = `
          <div class="workTime">
            <span class="attendance_2">休息</span>
          </div>
        `;
        return returnStr;
      }
      // 判断是否全天请假
      if (data.isRest == 0) {
        if (data.isLeave == 1 && data.leaveHours >= 8) {
          returnStr = `
         <div class="workTime">
                <span>请假${data.leaveHours}小时</span>
            </div>
          `;
        } else {
          // 上下班打卡1
          if (data.echoGoToWorkTime1 && data.echoGoOffWorkTime1) {
            returnStr += `
            <div class="workTime">
                <span>上下班</span>
                :
                <span class="${data.goToWorkTime1 ? 'success' : 'danger'}">${this.handleFormatReplace(data.goToWorkTime1, data.echoGoToWorkTime1, data.isReplace)}</span>
                -
                <span class="${data.goOffWorkTime1 ? 'success' : 'danger'}">${this.handleFormatReplace(data.goOffWorkTime1, data.echoGoOffWorkTime1, data.isReplace)}</span>
            </div>
          `
          }
          // 上下班打卡2
          if (data.echoGoToWorkTime2 && data.echoGoOffWorkTime2) {
            returnStr += `
            <div class="workTime">
                <span>上下班</span>
                :
                <span class="${data.goToWorkTime2 ? 'success' : 'danger'}">${this.handleFormatReplace(data.goToWorkTime2, data.echoGoToWorkTime2, data.isReplace)}</span>
                -
                <span class="${data.goOffWorkTime2 ? 'success' : 'danger'}">${this.handleFormatReplace(data.goOffWorkTime2, data.echoGoOffWorkTime2, data.isReplace)}</span>
            </div>
          `;
          }
          // 上下班打卡3
          if (data.echoGoToWorkTime3 && data.echoGoOffWorkTime3) {
            returnStr += `
            <div class="workTime">
                <span>上下班</span>
                :
                <span class="${data.goToWorkTime3 ? 'success' : 'danger'}">${this.handleFormatReplace(data.goToWorkTime3, data.echoGoToWorkTime3, data.isReplace)}</span>
                -
                <span class="${data.goOffWorkTime3 ? 'success' : 'danger'}">${this.handleFormatReplace(data.goOffWorkTime3, data.echoGoOffWorkTime3, data.isReplace)}</span>
            </div>
          `;
          }
        }
      }

      if (data.isInThisProject == 1) { // 判断是否本项目加班
        returnStr += `
              <div class="workTime">
                <span class="attendance_2">本项目加班${data.inThisHours}小时</span>
              </div>
            `;
      } else if (data.isOutExtProject == 1) { // 判断是否外出加班
        returnStr += `
              <div class="workTime">
                <span class="attendance_2">外项目加班${data.outExtHours}小时</span>
              </div>
            `;
      }

      return returnStr;
    },
    // 补卡格式化
    handleFormatReplace(workTime, echoWorkTime, isReplace) {
      let str = '缺卡';
      if (workTime) {
        if (isReplace == 1 && workTime == echoWorkTime) {
          str = '补卡';
        } else {
          str = workTime;
        }
      }
      return str;
    },
    //鼠标左右键控制横向滚动
    startDrag(event) {
      this.dragging = true;
      this.startX = event.clientX; // 记录鼠标按下的位置
      this.scrollLeft = this.$el.querySelector('.el-table__body-wrapper').scrollLeft; // 获取当前滚动位置
    },
    stopDrag() {
      this.dragging = false;
    },
    handleDrag(event) {
      if (this.dragging) {
        const dx = event.clientX - this.startX; // 计算鼠标移动的距离
        const newScrollLeft = this.scrollLeft - dx; // 计算新的滚动位置
        this.$el.querySelector('.el-table__body-wrapper').scrollLeft = newScrollLeft; // 设置新的滚动位置
      }
    }
  },
};
</script>
<style scoped>
.el-select {
  width: 100%;
}

.title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  text-align: left;
  color: black;
}

.attDetails {
  margin-top: 5px;
  text-align: left;
}

::v-deep .el-calendar__header {
  display: none;
}

::v-deep .prev {
  background: #f6f6f6;
}

::v-deep .next {
  background: #f6f6f6;
}

::v-deep .el-calendar-table thead th {
  color: #606266 !important;
  text-align: center;
}

::v-deep .el-calendar__body table thead th {
  color: #68a8d0;
}

/* ::v-deep .el-calendar-table {
  height: 100% !important;
} */

/* 内部小方格，可直接控制显示 */
::v-deep .el-calendar-table .el-calendar-day {
  height: 100% !important;
}

/* 非本月部分的文字灰色 */
::v-deep .el-calendar-table .next .el-calendar-day {
  color: #C0C4CC !important;
}

::v-deep .el-calendar-table .prev .el-calendar-day {
  color: #C0C4CC !important;
}

::v-deep .el-calendar__body {
  padding: 0;
  padding-bottom: 10px;
}

/*正常考勤*/
.attendance_1 {
  color: #11b95c;
}

/*加班考勤*/
.attendance_2 {
  color: #ff7d22;
}

/*补卡*/
.attendance_3 {
  color: #46a6ff;
}

/*请假*/
.attendance_4 {
  color: #9f9f9f;
}


::v-deep .workTime span {
  background-color: #ecf5ff;
  display: inline-block;
  height: 20px;
  padding: 0 5px;
  line-height: 19px;
  font-size: 12px;
  color: #409eff;
  border: 1px solid #d9ecff;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
}

::v-deep .success {
  background-color: #f0f9eb !important;
  border-color: #e1f3d8 !important;
  color: #11b95c !important
}

::v-deep .danger {
  background-color: #fef0f0 !important;
  border-color: #fde2e2 !important;
  color: #f56c6c !important
}
</style>
